import { ref, watch, type Ref } from "vue";
import { defineStore } from "pinia";
import { store } from "../index";
import { useSystemStoreHook } from "./system";
import { ElMessageBox } from "element-plus";

const useTableStore = defineStore("table", () => {
  const systemStore = useSystemStoreHook();
  const tableDatas: Ref<TableData[]> = ref([]);
  const standardGrade = ref({});

  let keyNameMap: any = {};

  watch(
    () => systemStore.tableConfigs,
    (val) => {
      keyNameMap = {};
      standardGrade.value = {};
      tableDatas.value = val.map((cfg, index) => {
        const tableName = cfg.name;
        const rowName = cfg.row;
        const colName = cfg.col;
        let rows: string[] = [];
        let cols: string[] = [];
        let calc = 0;

        for (let i = 0; i < systemStore.grades.length; i++) {
          const grade = systemStore.grades[i];
          if (grade.gradeName === cfg.row) {
            keyNameMap[cfg.row] = {
              tableIndex: index,
              type: "row"
            };
            rows = grade.options;
            calc += 1;
          }
          if (grade.gradeName === cfg.col) {
            const colMap: any = {};
            grade.options.forEach((c, i) => (colMap[c] = i));
            keyNameMap[cfg.col] = {
              tableIndex: index,
              type: "col",
              colMap
            };
            cols = grade.options;
            calc += 1;
          }
        }
        if (calc !== 2) {
          ElMessageBox.confirm(
            `配置文件存在异常，请联系管理员解决：统计表初始化时发生错误，列查无${cfg.col}或行查无${cfg.row}`,
            { type: "warning", showCancelButton: false }
          );
        }
        const firstCeil = `${colName}\\${rowName}`;
        const _rows = [firstCeil, ...rows, "偏档", "合计"];
        const _cols = [...cols, "偏档", "合计"];
        const data = _cols.map((c) => {
          const res: any = {};
          res[firstCeil] = c;
          rows.forEach((r) => (res[r] = 0));
          return { ...res, 偏档: 0, 合计: 0 };
        });
        standardGrade.value[rowName] = rows.length > 0 ? rows[0] : null;
        standardGrade.value[colName] = cols.length > 0 ? cols[0] : null;
        return {
          tableName,
          rowName,
          colName,
          rows: _rows,
          cols: _cols,
          data
        };
      });
    },
    { immediate: true }
  );

  function updateCeil(key1: string, grade1: string, key2: string, grade2: string, value: number) {
    const k1 = keyNameMap[key1];
    const k2 = keyNameMap[key2];
    let tableIndex: number;
    let col: number;
    let row: string;
    if (k1.tableIndex !== k2.tableIndex) {
      return;
    } else {
      tableIndex = k1.tableIndex;
    }
    if (k1.type === "row" && k2.type === "col") {
      col = k2.colMap[grade2];
      row = grade1;
    } else if (k1.type === "col" && k2.type === "row") {
      col = k1.colMap[grade1];
      row = grade2;
    } else {
      return;
    }
    tableDatas.value[tableIndex].data[col][row] = value;
  }

  function calcTable() {
    tableDatas.value.forEach((t) => {
      const firstCeil = `${t.colName}\\${t.rowName}`;
      // 最后两行数据，偏档和合计开头的两行
      const sum = { 偏档: 0, 合计: 0 };
      const diff = { 偏档: 0, 合计: 0 };
      t.data.forEach((item) => {
        // 遍历至最后两行数据不进行求和
        if (item[firstCeil] === "偏档" || item[firstCeil] === "合计") return;
        let itemSum = 0;
        let itemDiff = 0;
        for (const key in item) {
          if (key === "偏档" || key === "合计") continue;
          const val = item[key];
          // 累加求左侧每个档次的总数
          itemSum += val;
          // 累加求最底行每个档次的总数
          if (sum[key]) {
            sum[key] = val;
          } else {
            sum[key] += val;
          }
          if (standardGrade.value[t.rowName] && standardGrade.value[t.rowName] !== key) {
            // 累加求左侧每个档次的偏档数
            itemDiff += val;
            // 累加求最底行标准档次的总数
            if (diff[key]) {
              diff[key] = val;
            } else {
              diff[key] += val;
            }
          }
        }
        item["合计"] = itemSum;
        item["偏档"] = itemDiff;
      });
      for (const key in sum) {
        sum["合计"] += sum[key];
        if (standardGrade.value[t.rowName] && standardGrade.value[t.rowName] !== key) {
          sum["偏档"] += sum[key];
        }
      }
      for (const key in diff) {
        diff["合计"] += diff[key];
        if (standardGrade.value[t.rowName] && standardGrade.value[t.rowName] !== key) {
          diff["偏档"] += diff[key];
        }
      }
    });
  }

  return {
    tableDatas,
    updateCeil,
    calcTable
  };
});

export function useTableStoreHook() {
  return useTableStore(store);
}
